/*
 * ALE client program for chat
 *
 * Good for what ales ya.
 */
#include "ale.h"

int sockfd;
int connected;

void *thread0(void *param)
{
	char fromServer[MAX_RW+1];
	static char buf[BUFSIZ];
	int len;
	memset(buf, '\0', sizeof(buf));
	memset(fromServer, '\0', sizeof(fromServer));
	while ((len = read(sockfd, fromServer, sizeof(fromServer))) != 0)
	{
		fromServer[len] = '\0';
		strcat(buf, fromServer);
		if(buf[strlen(buf)-1] == '\n') {
			addLine(buf, AUTO);
			memset(buf, '\0', sizeof(buf));
		}
	}
	connected = 0;
	addLine("Server disconnected.\n", DISCONNECTED);
	close(sockfd);
	return param;
}

int main(int argc, char* argv[])
{
	struct sockaddr_in serv_addr;
	char toServer[BUFSIZ];
	pthread_t thread;

	if (argc != 2)
	{
		fprintf(stderr, "Correct usage: %s Address\n", argv[0]);
		exit(1);
	}

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		fputs("Socket returned null\n", stderr);
		exit(2);
	}

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT);
	serv_addr.sin_addr.s_addr = inet_addr(argv[1]);

	if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
	{
		fputs("Connection error\n", stderr);
		exit(3);
	}

	/*
	 * Ask for user name, send to server first
	 * off (before initializing Mug)
	 */
	for(;;)
	{
		printf("User name: ");
		fgets(toServer, sizeof(toServer), stdin);

		if(strlen(toServer) < MAX_CLIENT_NAME)
			break;
		else
			printf("Name must be under %d characters.\n", MAX_CLIENT_NAME);
	}
		write(sockfd, toServer, strlen(toServer));

	connected = 1;
	/* Initialize Mug */
	loadWindow();
	colorize();

	pthread_create(&thread, NULL, thread0, 0);

	while (connected)
	{
		getLine(toServer, sizeof(toServer));
		/*
		 * TODO: break up the read in buffer to  send only
		 * the MAX_RW size
		 */
		if (toServer[0] != '\n')
		{
			int i;
			if (strncmp(toServer, QUITS, strlen(QUITS)) == 0)
				break; /* leave the chat */
			for(i = 0; i < strlen(toServer);) {
				write(sockfd, toServer+i, MAX_RW);
				fsync(sockfd); /* FIXME: this causes warning of implicitness*/
				i += MAX_RW;
			}
		}
	}
	unloadWindow();
	return 0;
}

/*
 * TODO: Define coloring specs.
 */
void colorize(void) {
}
